import updateManager from './common/updateManager';
import {
  fetchUserCenter
} from 'services/usercenter/fetchUsercenter';

const defaultAllGoodsList = [
  {
    id: 0,
    name: '葱花饼',
    price: 350,
    unit: '个',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/1.jpg'
  },
  {
    id: 1,
    name: '稀饭',
    price: 150,
    unit: '位',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/2.jpg'
  },
  {
    id: 2,
    name: '小菜',
    price: 200,
    unit: '碟',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/8.jpg'
  },
  {
    id: 3,
    name: '煎鸡蛋',
    price: 200,
    unit: '个',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/7.png'
  },
  {
    id: 4,
    name: '茶叶蛋',
    price: 150,
    unit: '个',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/5.jpg'
  },
  {
    id: 5,
    name: '小菜（碗）',
    price: 700,
    unit: '碗',
    count: 0,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/9.png'
  },
  {
    id: 6,
    name: '小菜（外带）',
    price: 1400,
    unit: '公斤',
    count: 0,
    countIsDecimal: true,
    thumb: 'https://www.breakfast-dinner.xin/chb_eatery_images/10.jpg'
  }
];

// app.js
App({
  data:{
    socketHandler: null,
    loginDone: false,
    loginData:{
      userInfo: {
        avatarUrl: '',
        nickName: '请登录',
        phoneNumber: '',
        address: '',
        authorizations: '',
      },
      token: '',
      openid: '',
      shopIdForAdmin: null,
    },
    updataUserPageLoginDataCallback: null,
    setGetAllGoodsDoneCallback: null,
    shops: {
      index: 1,  // 默认兴业园，去掉大修厂
      shopsDetails: [
        {
          id: 0,
          name: "请选择店铺",
          tag: ""
        },
        {
          id: 1,
          shopId: 1,
          name: "昌吉葱花饼店（兴业园店）",
          shopAddr: '哈密市军民巷兴业园小区底商',
          tag: "哈密市军民巷兴业园底商\n欢迎光临",
          workStatus: 1,
          startHour: 7,
          startMinute: 0,
          endHour: 13,
          endMinute: 0
        },
        {
          id: 2,
          shopId: 2,
          name: "昌吉葱花饼店（大修厂店）",
          shopAddr: '大修厂',
          tag: "大修厂\n欢迎光临",
          workStatus: 1,
          startHour: 6,
          startMinute: 0,
          endHour: 13,
          endMinute: 0
        }
      ]
    },
    toPayAction: false,
    global_urls:{
      home_url: 'http://www.breakfast-dinner.xin/chb_eatery_images/home.jpg',
      urlEatAtHere: 'http://www.breakfast-dinner.xin/chb_eatery_images/eatAtHere.png',
      urlEatAtThere: 'http://www.breakfast-dinner.xin/chb_eatery_images/eatAtThere.png',
      locationIcon: 'http://www.breakfast-dinner.xin/chb_eatery_images/location.png',
      root_url: 'https://www.breakfast-dinner.xin',
      base_url: 'https://www.breakfast-dinner.xin/emall/api/wchat',
      general_msg_voice: 'https://www.breakfast-dinner.xin/chb_eatery_images/msg.wav',
      new_msg_voice: 'https://www.breakfast-dinner.xin/chb_eatery_images/new_msg.mp3',
      musics:[],
      goodsThumb:[
        "https://www.breakfast-dinner.xin/chb_eatery_images/1.jpg",
        "https://www.breakfast-dinner.xin/chb_eatery_images/2.jpg",
        "https://www.breakfast-dinner.xin/chb_eatery_images/8.jpg",
        "https://www.breakfast-dinner.xin/chb_eatery_images/7.png",
        "https://www.breakfast-dinner.xin/chb_eatery_images/5.jpg",
        "https://www.breakfast-dinner.xin/chb_eatery_images/9.png",
        "https://www.breakfast-dinner.xin/chb_eatery_images/10.jpg"
      ],
      getLoginUrl: function() { return `${this.base_url}/login`;},
      getBindPhoneUrl: function() { return `${this.base_url}/bindPhone`;},
      getWxpaySignStr: function() { return `${this.base_url}/getWxpaySignStr`;},
      getWxprepayIdUrl: function() { return `${this.base_url}/wechatPrepayRequest`;},
      getAllGoodsUrl: function() { return `${this.base_url}/product/list`;},
      getPrepayUrl: function() { return `${this.base_url}/prepay`;},
      getOrderDetailUrl: function() { return `${this.base_url}/order/getOrderDetail`;},
      getPayByOrderUrl: function() { return `${this.base_url}/payByOrder`;},
      getRefreshOrderStatusUrl: function() { return `${this.base_url}/refreshOrderStatus`;},
      getCancelOrderUrl: function() { return `${this.base_url}/cancelOrder`;},
      getHistoryOrdersUrl: function() { return `${this.base_url}/order/getHistoryOrders`;},
      getAdminHistoryOrdersUrl: function() { return `${this.base_url}/order/admin/getHistoryOrders`;},
      getAdminHistoryOrdersV2Url: function() { return `${this.base_url}/order/admin/getHistoryOrdersV2`;},
      getOrderRefundUrl: function() { return `${this.base_url}/order/orderRefund`;},
      getCancelRefundUrl: function() { return `${this.base_url}/order/cancelRefund`;},
      getFinishOrderUrl: function() { return `${this.base_url}/order/finishOrder`;},
      getDoRefundAdminUrl: function() { return `${this.base_url}/doRefundAdmin`;},
      getShopsUrl: function() { return `${this.base_url}/public/getShops`;},
      getTriggleWorkStatusUrl: function() { return `${this.base_url}/admin/triggleWorkStatus`;},
      getChangeWorkTimeUrl: function() { return `${this.base_url}/admin/changeWorkTime`;},
    },
    globalData:{
      order:{
        unpay:{
          id: null,
          totalPrice: 0,
          goods:[],
          addGoods: [],
          postType: 0
        },
        currentOrderNo: null
      },
      allGoodsList: '',
      additionalGoods: '',
    },
  },

  onLaunch: function () {
    console.log("------------in onLaunch-----------")
    var that = this;

    // 1. handle login
    wx.getStorage({
      key: "key",
      encrypt: true, // 若开启加密存储，setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
      success(res) {
        console.log('获取存储信息', res.data);
        that.data.loginData = res.data;

        that.data.loginDone = true;
        that.data.updataUserPageLoginDataCallback();
        // that.connectWebSocket();

        // 需要检查微信session是否过期
        // wx.checkSession({
        //   success () {
        //     // session_key 未过期，并且在本生命周期一直有效
        //     console.log('微信session有效')
        //     that.data.loginDone = true;
        //   },
        //   fail () {
        //     // session_key 已经失效，需要重新执行登录流程
        //     console.log('微信session无效，需要重新登录')
        //     that._userLogin();
        //   }
        // })
      },
      fail(e){
        // 内部存储中没有key
        that._userLogin();
      }
    })

  },

  getAllGoodsList(){
    var that = this;

    wx.request({
      url: this.data.global_urls.getAllGoodsUrl(),
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        pageNum: 1,
        pageSize: 10,
        categoryId: that.data.shops.index + 1
      },
      success: (res) => {
        console.log('wchatlogin返回 : ', res.data)
        if (res.data.status === 10000) {
          that.data.globalData.allGoodsList = res.data.data.goods;
          that.data.globalData.additionalGoods = res.data.data.additionalGoods;
          if(that.data.setGetAllGoodsDoneCallback){
            that.data.setGetAllGoodsDoneCallback();
          }
        } else {
          
        }
      },
    })
  },

  onShow: function () {
    updateManager();
  },
  
  _userLogin(preCallback, postCallback){
    var that = this;
    fetchUserCenter(preCallback, this.data.global_urls.getLoginUrl()).then((data) => {
      console.log('登录成功在app.js -> _userLogin')
      
      setTimeout(()=>{
        that.data.loginData = data;
        if(postCallback){
          postCallback(data);
        }else{
        }
        wx.hideToast();
        that.data.loginDone = true;
        that.data.updataUserPageLoginDataCallback();
      }, 0)
    })
  },

  _needReLogin(preCallback, postCallback){
    var that = this;

    wx.removeStorage({
      key: 'key',
      success (res) {
        console.log(res)
      }
    })

    this.data.loginData.userInfo.avatarUrl = '';
    this.data.loginData.userInfo.nickName = '请登录';
    this.data.loginData.userInfo.phoneNumber = '';
    this.data.loginData.token = '';
    this.data.loginData.openid = '';

    // 弹框请登录
    wx.showActionSheet({
      itemList: ['微信一键登录'],
      success (res) {
        if(0 === res.tapIndex){
          wx.showToast({
            title: '正在登录',
            icon: 'loading',
            duration: 30000,
            mask: true
          })
          that._userLogin(preCallback, postCallback);
        }
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  
  _doPay(payArgs, completeCallback){
    wx.requestPayment({
      timeStamp: payArgs.timeStamp,
      nonceStr: payArgs.nonceStr,
      package: payArgs.packageVal,
      signType: payArgs.signType,
      paySign: payArgs.paySign,
      success (res) {
        console.log("支付成功", res)
       },
      fail (res) {
        console.log("支付失败", res)
      },
      complete(e){
        if(completeCallback){
          completeCallback();
        }
      }
    })
  },

  _refreshAllGoodsList(id, count){
    this.data.globalData.allGoodsList.forEach((item) => {
      if(item.id === id){
        item.count = count;
        // console.log('订单页面刷新全局数据 globalData: ', app.data.globalData)
        return true;
      }
    })
  },

  _getReasonableWorkStatus(now, status, shop){
    // 获取当前小时数
    const currentHour = now.getHours();
    const currentMin = now.getMinutes();
    
    if(!shop.startHour){
      return status;
    }
    const sHour = shop.startHour;
    const sMin = shop.startMinute;
    const eHour = shop.endHour;
    const eMin = shop.endMinute;
    if((currentHour*60+currentMin < sHour*60+sMin) ||
        (currentHour*60+currentMin > eHour*60+eMin)){
      status = 0;
    }
    return status;
  }
})
